import React, { Component } from 'react'
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import './login.less'
import {reqLogin} from '../../api'
import memoryUtils from '../../utils/memoryUtils';
import storageUtils from '../../utils/storageUtils'
import { Redirect } from 'react-router-dom';

// 登录
 export default  class Login extends Component {
  // 发送表单的请求
  onFinish = async(values) => {
    const {username,password }=values
    const response=await reqLogin(username,password)
     const result=response.data
     if(result.status===0){
      message.success("登录成功")
      console.log(result)
      // 保存user
      const user=result.user
      memoryUtils.user=user//存在内存中
      storageUtils.saveUser(user)//保存到本地
      // 跳转页面
      this.props.history.replace('/home')
     } else{
       message.error(result.msg)
     }
    console.log('Finish:', values);
  };
  render() {
     // 如果用户已经登录跳转管理页面
  const user=memoryUtils.user
  if(JSON.stringify(user) !== "{}"){
      return <Redirect to='/'/>
    }
    return (
      <div className='login'>
        <header className='login-header'>
        <h1>后台管理系统</h1> 
        </header>
        <section className='login-content'>
          <h2>用户登录</h2>
          <div>
           <Form  onFinish={this.onFinish} className="login-form">
           <Form.Item
            name="username"
            // 声明式验证
            rules={[
              { required: true, whitespace:true,message: '请输入用户名!' },
              { min: 4, message: '长度不小于4' },
              { max: 12, message: '长度不大于12' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名必须是英文字母或下划线' },//正则表达式
            ]}
      >
            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
        </Form.Item>
       <Form.Item
           name="password"
           rules={[
             { required: true, message: '请输入密码!' },
              { min: 4, message: '密码不小于4' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '密码必须是英文字母或下划线' },//正则表达式
            ]}
      >
          <Input
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          placeholder="Password"
        />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
           登录
          </Button>
        </Form.Item>
      </Form>
          </div>
        </section>
      </div>
    );
    
  }

}



